package hu.issue.web;

import hu.issue.ejb.ProjectService;
import hu.issue.entity.Milestone;
import hu.issue.exceptions.ProjectNotFoundException;
import hu.issue.framework.web.Constants;
import hu.issue.framework.web.controller.AbstractFormController;
import hu.issue.framework.web.controller.Inject;
import hu.issue.framework.web.controller.RequiredRole;
import hu.issue.framework.web.validation.ErrorMessages;
import hu.issue.framework.web.validation.IntegerValidator;
import hu.issue.framework.web.validation.RequestValidation;
import hu.issue.framework.web.validation.RequiredValidator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RequiredRole(Constants.ROLE_PROJECTOWNER)
public class NewMilestoneController extends AbstractFormController {
	@Inject
	private ProjectService projectService;

	@Override
	protected String handleSubmission(final HttpServletRequest request, final HttpServletResponse response, final ErrorMessages messages) throws Exception {
		final int projectId = Integer.parseInt(request.getParameter("projectId"));
		try {
			this.projectService.addMilestone(projectId, new Milestone(request.getParameter("milestone")));
			return "redirect:project.do?projectId=" + projectId;
		} catch (final ProjectNotFoundException ex) {
			messages.addMessage("Nincs ilyen projekt");
			return getFormView();
		}

	}

	@Override
	protected void buildValidation(final RequestValidation validation) {
		validation.addValidator(new RequiredValidator("milestone", "Név kötelező"));
		validation.addValidator(new RequiredValidator("projectId", "Projekt azonosíó kötelező"));
		validation.addValidator(new IntegerValidator("projectId", "Projekt azonosító szám kell legyen"));
	}
}
